package usermodel

import (
	"encoding/gob"
	"web_server/model"

	"golang.org/x/crypto/bcrypt"
)

type UserModel struct {
	Id       int64  `json:"id"`
	Namecode string `json:"name"`
	Username string `json:"user_name"`
	Role     int    `json:"role"`
}

func init() {
	gob.Register(UserModel{})
}

func encodePassword(pwd string) string {
	hash, err := bcrypt.GenerateFromPassword([]byte(pwd), bcrypt.DefaultCost)
	if err != nil {
		return ""
	}
	return string(hash)
}

func comparePassword(comPwd, pwdHash string) bool {
	err := bcrypt.CompareHashAndPassword([]byte(pwdHash), []byte(comPwd))
	return err == nil
}

func LoginCheck(namecode, password string) bool {
	var dbpsw string
	if err := model.DBSlaveRand().Get(&dbpsw, "SELECT password FROM t_user where namecode = ?", namecode); err != nil {
		return false
	}
	return comparePassword(password, dbpsw)
}

func LoginAction(namecode string) (user UserModel) {
	if err := model.DBSlaveRand().Get(&user, "SELECT id, namecode, username, role FROM t_user where username = ?", namecode); err != nil {
		panic(err)
	}
	return
}
